import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'
import { storeLogger } from '@/utils/logger'

export const useJobsStore = defineStore('jobs', () => {
  // 状态
  const jobs = ref([])
  const loading = ref(false)
  const total = ref(0)           // 当前筛选条件下的总数（用于分页）
  const totalAll = ref(0)        // 全部数据的总数（用于统计卡片显示）
  const statusStats = ref({})    // 全部数据的状态统计（用于统计卡片显示）
  const currentPage = ref(1)
  const pageSize = ref(20)
  
  // 搜索条件
  const searchForm = ref({
    job_name: '',
    status: '',
    monitor_status: '',
    fields: []
  })
  
  // 排序条件（默认按更新时间降序）
  const sortField = ref('last_update_time')
  const sortOrder = ref('desc')
  
  // 获取全部数据统计（无搜索条件）
  // 注意：现在后端在每次请求中都会返回全局统计，这个方法已不再需要单独调用
  const fetchAllStats = async () => {
    try {
      const response = await api.get('/jobs', { 
        params: { page: 1, pageSize: 20 } // 只获取第一页即可，统计数据会一起返回
      })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload
      
      // 后端现在直接返回全局统计
      if (data.hasOwnProperty('total_all')) {
        totalAll.value = data.total_all
      }
      if (data.hasOwnProperty('status_stats')) {
        statusStats.value = data.status_stats
      }
      
      storeLogger.info('All stats fetched successfully', { 
        totalAll: totalAll.value,
        statusStats: statusStats.value
      })
    } catch (error) {
      storeLogger.error('Failed to fetch all stats', error)
    }
  }

  // 获取作业列表
  const fetchJobs = async (params = {}) => {
    try {
      loading.value = true
      const queryParams = {
        ...searchForm.value,
        page: currentPage.value,
        pageSize: pageSize.value,
        sort: sortField.value,
        order: sortOrder.value,
        ...params
      }
      
      // 如果传入了字段参数，添加到查询参数中
      if (params.fields && params.fields.length > 0) {
        queryParams.fields = params.fields
      }
      
      // 如果传入了字段排序参数，添加到查询参数中
      if (params.field_order && params.field_order.length > 0) {
        queryParams.field_order = JSON.stringify(params.field_order)
      }
      
      // 如果传入了排序参数，覆盖默认排序
      if (params.sort) {
        sortField.value = params.sort
        queryParams.sort = params.sort
      }
      if (params.order) {
        sortOrder.value = params.order
        queryParams.order = params.order
      }
      
      // 清理空值
      Object.keys(queryParams).forEach(key => {
        if (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === undefined) {
          delete queryParams[key]
        }
      })
      
      // 记录查询参数
      storeLogger.debug('Fetching jobs with params', queryParams)
      
      const response = await api.get('/jobs', { params: queryParams })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload
      jobs.value = data.rows || []
      // 确保使用后端返回的真实总数，即使为0也要使用
      total.value = data.hasOwnProperty('total') ? data.total : jobs.value.length
      
      // 后端现在直接返回全局统计数据（不管是否有筛选条件）
      if (data.hasOwnProperty('total_all')) {
        totalAll.value = data.total_all
      }
      if (data.hasOwnProperty('status_stats')) {
        statusStats.value = data.status_stats
      }
      
      // 调试信息：查看返回的数据结构
      storeLogger.info('Jobs fetched successfully', { 
        count: jobs.value.length, 
        total: total.value,
        totalAll: totalAll.value,
        statusStats: statusStats.value,
        page: currentPage.value 
      })
      
      return response.data
    } catch (error) {
      storeLogger.error('Failed to fetch jobs', error)
      ElMessage.error('获取作业列表失败')
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 注册新作业
  const registerJob = async (jobData) => {
    try {
      loading.value = true
      const response = await api.post('/jobs/register', jobData)
      // 不在这里显示成功消息，由调用方处理
      return response.data
    } catch (error) {
      storeLogger.error('Job registration failed', error)
      ElMessage.error('作业注册失败')
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 停止作业
  const stopJob = async (jobName, options = {}) => {
    try {
      loading.value = true
      const { savepoint = false, max_retries = 3, retry_interval = 3, wait_for_stop = 5, flink_env } = options
      const response = await api.post(`/jobs/${jobName}/stop`, {
        savepoint,
        max_retries,
        retry_interval,
        wait_for_stop,
        flink_env
      })
      
      if (response.data.message) {
        ElMessage.success(response.data.message)
      } else {
        ElMessage.success('作业停止成功')
      }
      
      // 由调用方决定是否刷新列表
      return response.data
    } catch (error) {
      storeLogger.error('停止作业失败:', error)
      const errorMsg = error.response?.data?.error || '停止作业失败'
      ElMessage.error(errorMsg)
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 重启作业
  const restartJob = async (jobName, jobData) => {
    try {
      loading.value = true
      const response = await api.post(`/jobs/${jobName}/restart`, jobData)
      ElMessage.success('作业重启成功')
      // 由调用方决定是否刷新列表
      return response.data
    } catch (error) {
      storeLogger.error('重启作业失败:', error)
      ElMessage.error('重启作业失败')
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 批量停止作业
  const bulkStopJobs = async (jobNames, options = {}) => {
    try {
      loading.value = true
      const { 
        savepoint = false, 
        interval = 5, 
        max_retries = 3, 
        retry_interval = 3, 
        wait_for_stop = 5,
        flink_env
      } = options
      
      const response = await api.post('/jobs/bulk-stop', {
        job_names: jobNames,  // 修正参数名，后端期望 job_names
        savepoint,
        interval,
        max_retries,
        retry_interval,
        wait_for_stop,
        flink_env
      })
      
      // 适配后端统一数据格式
      const { success_count = 0, failed_count = 0, total_count = 0, stopped_jobs = [] } = response.data.data || {}
      ElMessage.success(`批量停止完成: 成功 ${success_count} 个, 失败 ${failed_count} 个, 总计 ${total_count} 个`)
      
      // 显示详细结果
      if (stopped_jobs && stopped_jobs.length > 0) {
        const failedJobs = stopped_jobs.filter(r => !r.success)
        if (failedJobs.length > 0) {
          storeLogger.warn('部分作业停止失败:', failedJobs)
          ElMessage.warning(`有${failedJobs.length}个作业停止失败，请查看控制台了解详情`)
        }
      }
      
      // 由调用方决定是否刷新列表
      return response.data
    } catch (error) {
      storeLogger.error('批量停止作业失败:', error)
      const errorMsg = error.response?.data?.error || '批量停止作业失败'
      ElMessage.error(errorMsg)
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 批量重启作业
  const bulkRestartJobs = async (jobNames, options = {}) => {
    try {
      loading.value = true
      const response = await api.post('/jobs/bulk-restart', {
        job_names: jobNames,
        ...options
      })
      
      // 适配后端统一数据格式
      const { success_count = 0, failed_count = 0, total_count = 0 } = response.data.data || {}
      ElMessage.success(`批量重启完成: 成功 ${success_count} 个, 失败 ${failed_count} 个`)
      
      // 由调用方决定是否刷新列表
      return response.data
    } catch (error) {
      storeLogger.error('批量重启作业失败:', error)
      ElMessage.error('批量重启作业失败')
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 批量删除作业（清空表）
  const bulkDelete = async () => {
    try {
      loading.value = true
      const response = await api.post('/jobs/bulk-delete', {
        confirm: true
      })
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      storeLogger.error('批量删除失败:', error)
      return {
        success: false,
        message: error.response?.data?.error || '删除失败'
      }
    } finally {
      loading.value = false
    }
  }
  
  // 停止监控作业
  const stopMonitorJob = async (jobName) => {
    try {
      const response = await api.post(`/jobs/${jobName}/stop-monitor`)
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      storeLogger.error('停止监控失败:', error)
      return {
        success: false,
        message: error.response?.data?.error || '停止监控失败'
      }
    }
  }
  
  // 恢复监控作业
  const startMonitorJob = async (jobName) => {
    try {
      const response = await api.post(`/jobs/${jobName}/start-monitor`)
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      storeLogger.error('恢复监控失败:', error)
      return {
        success: false,
        message: error.response?.data?.error || '恢复监控失败'
      }
    }
  }
  
  // 切换监控状态
  const toggleManualStopped = async (jobName, manualStopped) => {
    try {
      const response = await api.post(`/jobs/${jobName}/toggle-manual-stopped`, {
        manual_stopped: manualStopped
      })
      return response.data  // 直接返回后端数据
    } catch (error) {
      storeLogger.error('切换监控状态失败:', error)
      return {
        success: false,
        message: error.response?.data?.error || '切换监控状态失败'
      }
    }
  }
  
  // 切换告警开关状态
  const toggleAlertEnabled = async (jobName, isAlertEnabled) => {
    try {
      const response = await api.post(`/jobs/${jobName}/toggle-alert-enabled`, {
        is_alert_enabled: isAlertEnabled
      })
      return response.data  // 直接返回后端数据
    } catch (error) {
      storeLogger.error('切换告警开关失败:', error)
      return {
        success: false,
        message: error.response?.data?.error || '切换告警开关失败'
      }
    }
  }
  
  // 切换自动恢复状态
  const toggleAutoRecovery = async (jobName, autoRecovery) => {
    try {
      const response = await api.post(`/jobs/${jobName}/toggle-auto-recovery`, {
        auto_recovery: autoRecovery
      })
      return response.data  // 直接返回后端数据
    } catch (error) {
      storeLogger.error('切换自动恢复状态失败:', error)
      return {
        success: false,
        message: error.response?.data?.error || '切换自动恢复状态失败'
      }
    }
  }
  
  // 批量停止监控
  const bulkStopMonitor = async (jobNames = []) => {
    try {
      const response = await api.post('/jobs/bulk-stop-monitor', {
        job_names: jobNames
      })
      return response.data  // 直接返回后端数据，不再包装
    } catch (error) {
      storeLogger.error('批量停止监控失败:', error)
      return {
        success: false,
        message: error.response?.data?.error || '批量停止监控失败'
      }
    }
  }
  
  // 批量停止自动恢复
  const bulkStopRecovery = async (jobNames = []) => {
    try {
      const response = await api.post('/jobs/bulk-stop-recovery', {
        job_names: jobNames
      })
      return response.data  // 直接返回后端数据，不再包装
    } catch (error) {
      storeLogger.error('批量停止自动恢复失败:', error)
      return {
        success: false,
        message: error.response?.data?.error || '批量停止自动恢复失败'
      }
    }
  }
  
  // 批量开始监控
  const bulkStartMonitor = async (jobNames = []) => {
    try {
      const response = await api.post('/jobs/bulk-start-monitor', {
        job_names: jobNames
      })
      return response.data  // 直接返回后端数据，不再包装
    } catch (error) {
      storeLogger.error('批量开始监控失败:', error)
      return {
        success: false,
        message: error.response?.data?.error || '批量开始监控失败'
      }
    }
  }
  
  // 批量开始自动恢复
  const bulkStartRecovery = async (jobNames = []) => {
    try {
      const response = await api.post('/jobs/bulk-start-recovery', {
        job_names: jobNames
      })
      return response.data  // 直接返回后端数据，不再包装
    } catch (error) {
      storeLogger.error('批量开始自动恢复失败:', error)
      return {
        success: false,
        message: error.response?.data?.error || '批量开始自动恢复失败'
      }
    }
  }
  
  // 批量关闭告警
  const bulkDisableAlert = async (jobNames = []) => {
    try {
      const response = await api.post('/jobs/bulk-disable-alert', {
        job_names: jobNames
      })
      return response.data  // 直接返回后端数据，不再包装
    } catch (error) {
      storeLogger.error('批量关闭告警失败:', error)
      return {
        success: false,
        message: error.response?.data?.error || '批量关闭告警失败'
      }
    }
  }
  
  // 批量开启告警
  const bulkEnableAlert = async (jobNames = []) => {
    try {
      const response = await api.post('/jobs/bulk-enable-alert', {
        job_names: jobNames
      })
      return response.data  // 直接返回后端数据，不再包装
    } catch (error) {
      storeLogger.error('批量开启告警失败:', error)
      return {
        success: false,
        message: error.response?.data?.error || '批量开启告警失败'
      }
    }
  }
  
  // 更新作业参数
  const updateJobArgs = async (jobName, programArgs) => {
    try {
      const response = await api.post(`/jobs/${jobName}/update-args`, { programArgs })
      ElMessage.success('作业参数更新成功')
      // 由调用方决定是否刷新列表
      return response.data
    } catch (error) {
      storeLogger.error('更新作业参数失败:', error)
      ElMessage.error('更新作业参数失败')
      throw error
    }
  }
  
  // 更新作业恢复次数
  const updateJobAttempts = async (jobName, attempts) => {
    try {
      const response = await api.post(`/jobs/${jobName}/update-attempts`, attempts)
      // 不在这里显示成功消息和刷新，由调用方处理
      return response.data  // 直接返回后端数据
    } catch (error) {
      storeLogger.error('更新恢复次数失败:', error)
      return {
        success: false,
        message: error.response?.data?.error || '更新恢复次数失败'
      }
    }
  }
  
  // 更新作业完整信息
  const updateJob = async (jobName, jobData) => {
    try {
      const response = await api.post(`/jobs/${jobName}/update-job`, jobData)
      return response.data  // 直接返回后端数据
    } catch (error) {
      storeLogger.error('更新作业失败:', error)
      return {
        success: false,
        message: error.response?.data?.error || '更新作业失败'
      }
    }
  }
  
  
  // 删除作业
  const deleteJob = async (jobName) => {
    try {
      const response = await api.post(`/jobs/${jobName}/delete`)
      ElMessage.success('作业删除成功')
      // 刷新列表时不调用fetchJobs，由调用方处理刷新
      return response.data
    } catch (error) {
      storeLogger.error('删除作业失败:', error)
      ElMessage.error('删除作业失败')
      throw error
    }
  }
  
  // 重置搜索条件
  const resetSearch = () => {
    searchForm.value = {
      job_name: '',
      status: '',
      monitor_status: '',
      fields: []
    }
    currentPage.value = 1
  }
  
  return {
    // 状态
    jobs,
    loading,
    total,
    totalAll,
    statusStats,
    currentPage,
    pageSize,
    searchForm,
    sortField,
    sortOrder,
    
    // 方法
    fetchJobs,
    fetchAllStats,
    registerJob,
    stopJob,
    restartJob,
    bulkStopJobs,
    bulkRestartJobs,
    bulkDelete,
    stopMonitorJob,
    startMonitorJob,
    toggleManualStopped,
    toggleAlertEnabled,
    toggleAutoRecovery,
    bulkStopMonitor,
    bulkStopRecovery,
    bulkStartMonitor,
    bulkStartRecovery,
    bulkDisableAlert,
    bulkEnableAlert,
    updateJobArgs,
    updateJobAttempts,
    updateJob,
    deleteJob,
    resetSearch
  }
})
